import React, { useState, useEffect } from 'react';
import styles from './index.module.css';
import { format, parse, isValid } from 'date-fns';

const TimestampConverter = () => {
  const [timestamp, setTimestamp] = useState('');
  const [dateTimeInput, setDateTimeInput] = useState('');
  const [convertedDate, setConvertedDate] = useState('');
  const [convertedTimestamp, setConvertedTimestamp] = useState('');
  
  const [history, setHistory] = useState([]);
  const [outputUnit, setOutputUnit] = useState('seconds'); // 日期转时间戳的单位
  const [inputUnit, setInputUnit] = useState('seconds'); // 时间戳转日期的单位
  const [error, setError] = useState('');
  const [currentTimestamp, setCurrentTimestamp] = useState('');

  useEffect(() => {
    const updateCurrentTimestamp = () => {
      const now = new Date();
      const ts = inputUnit === 'seconds' ? Math.floor(now.getTime() / 1000) : now.getTime();
      setCurrentTimestamp(ts.toString());
    };

    updateCurrentTimestamp();
    const interval = setInterval(updateCurrentTimestamp, 1000);
    return () => clearInterval(interval);
  }, [inputUnit]);

  // 处理时间戳输入变化
  const handleTimestampChange = (e) => {
    setTimestamp(e.target.value);
    setError('');
  };

  // 处理日期时间输入变化
  const handleDateTimeInputChange = (e) => {
    setDateTimeInput(e.target.value);
    setError('');
  };

  // 转换时间戳为日期
  const handleConvertTimestamp = () => {
    setError('');
    setConvertedDate('');

    try {
      if (!timestamp) throw new Error('请输入时间戳');

      const num = Number(timestamp);
      if (isNaN(num)) throw new Error('请输入有效的数字');

      const date = new Date(inputUnit === 'seconds' ? num * 1000 : num);
      if (date.toString() === 'Invalid Date') throw new Error('无效的时间戳');

      setConvertedDate(format(date, 'yyyy-MM-dd HH:mm:ss'));
      setHistory(prev => [
        ...prev,
        {
          type: 'timestamp-to-date',
          input: timestamp,
          inputUnit: inputUnit,
          result: format(date, 'yyyy-MM-dd HH:mm:ss'),
          time: new Date().toLocaleTimeString()
        }
      ]);
    } catch (err) {
      setError(err.message);
    }
  };

  // 转换日期为时间戳
  const handleConvertDate = () => {
    setError('');
    setConvertedTimestamp('');

    try {
      if (!dateTimeInput) throw new Error('请选择日期时间');

      const date = new Date(dateTimeInput);
      if (date.toString() === 'Invalid Date') throw new Error('无效的日期时间');

      const timestamp = date.getTime();
      const result = outputUnit === 'seconds' ? Math.floor(timestamp / 1000) + ' 秒' : timestamp + ' 毫秒';
      setConvertedTimestamp(result);
      setHistory(prev => [
        ...prev,
        {
          type: 'date-to-timestamp',
          input: dateTimeInput,
          outputUnit: outputUnit,
          result: result,
          time: new Date().toLocaleTimeString()
        }
      ]);
    } catch (err) {
      setError(err.message);
    }
  };

  useEffect(() => {
      // 设置页面标题
      document.title = "时间戳转换器 - 工具集";

      // 设置描述元标签
      const descriptionMeta = document.querySelector('meta[name="description"]');
      if (descriptionMeta) {
        descriptionMeta.content = "免费在线Unix时间戳与日期时间相互转换工具，支持秒和毫秒单位，精确转换各种时间格式。";
      } else {
        const meta = document.createElement('meta');
        meta.name = "description";
        meta.content = "免费在线Unix时间戳与日期时间相互转换工具，支持秒和毫秒单位，精确转换各种时间格式。";
        document.head.appendChild(meta);
      }
    }, []);

    return (
        <div className={styles.container}>
  
        <div className={styles.card}>
        <h2 className={styles.title}>时间戳转换器</h2>
        <div className={styles.panelsContainer}>
          {/* 左侧面板：时间戳转时间 */}
          <div className={styles.panel}>
            <h3 className={styles.panelTitle}>Unix时间戳 → 时间</h3>

            <div className={styles.inputGroup}>
              <label className={styles.inputLabel}>时间戳</label>
              <div className={styles.inputGroup}>
                <input
                  type="number"
                  value={timestamp}
                  onChange={handleTimestampChange}
                  placeholder="请输入时间戳 (例如: 1673122287)"
                  className={styles.inputField}
                />
              </div>
              <label className={styles.inputLabel}>单位</label>
              <select
                  value={inputUnit}
                  onChange={(e) => setInputUnit(e.target.value)}
                  className={styles.selectField}
                >
                  <option value="seconds">秒(s)</option>
                  <option value="milliseconds">毫秒(ms)</option>
                </select>
              <div className={styles.divider}></div>
            </div>

            <button
              onClick={handleConvertTimestamp}
              className={styles.convertButton}
              >转换</button>

            {convertedDate && (
              <div className={styles.resultContainer}>
                <div className={styles.resultTitle}>转换结果:</div>
                <div className={styles.resultValue}>{convertedDate}</div>
              </div>
            )}

            <div className={styles.currentTimestamp}>
              当前时间戳: {currentTimestamp} {inputUnit === 'seconds' ? '秒' : '毫秒'}
            </div>
          </div>

          {/* 右侧面板：时间转时间戳 */}
          <div className={styles.panel}>
            <h3 className={styles.panelTitle}>时间 → Unix时间戳</h3>

            <div className={styles.inputGroup}>
              <label className={styles.inputLabel}>时间</label>
              <input
                type="text"
                value={dateTimeInput}
                onChange={(e) => {
                  const input = e.target.value;
                  setDateTimeInput(input);
                  // 尝试解析多种时间格式
                  try {
                    const parsedDate = parse(input, 'yyyy-MM-dd HH:mm:ss', new Date());
                    if (!isValid(parsedDate)) {
                      // 尝试其他格式
                      const formats = ['yyyy-MM-dd HH:mm:ss', 'yyyy/MM/dd HH:mm:ss', 'yyyy-MM-dd HH:mm', 'yyyy/MM/dd HH:mm', 'yyyy-MM-dd', 'yyyy/MM/dd', 'MM/dd/yyyy', 'dd-MM-yyyy', 'dd/MM/yyyy', 'yyyyMMdd', 'yyyy-MM-ddTHH:mm:ss', 'yyyy-MM-ddTHH:mm', 'yyyy年MM月dd日', 'yyyy年MM月dd日 HH:mm:ss', 'yyyy-MM-dd HH:mm:ss.SSS', 'yyyy-MM-dd HH:mm:ss.S', 'yyyyMMddHHmmss', 'yyyyMMddHHmm', 'yyyyMMddHHmmssSSS', 'yyyyMMddHHmmssSS'];
                      for (const fmt of formats) {
                        const d = parse(input, fmt, new Date());
                        if (isValid(d)) {
                          setDateTimeInput(format(d, 'yyyy-MM-dd HH:mm:ss'));
                          break;
                        }
                      }
                    }
                  } catch (err) {
                    // 解析失败保持原样
                  }
                }}
                className={styles.inputField}
                placeholder="输入时间 (支持格式: 2023-10-01 12:30:45、2023/10/01等)"
              />
            </div>

            <div className={styles.inputGroup}>
              <label className={styles.inputLabel}>单位</label>
              <select
                value={outputUnit}
                onChange={(e) => setOutputUnit(e.target.value)}
                className={styles.selectField}
              >
                <option value="seconds">秒(s)</option>
                <option value="milliseconds">毫秒(ms)</option>
              </select>
            </div>

            <button
              onClick={handleConvertDate}
              className={styles.convertButton}
              >转换</button>

            {convertedTimestamp && (
              <div className={styles.resultContainer}>
                <div className={styles.resultTitle}>转换结果:</div>
                <div className={styles.resultValue}>{convertedTimestamp}</div>
              </div>
            )}
          </div>
        </div>

        {error && <div className={styles.error}>{error}</div>}
      </div>

      <div className={styles.historyPanel}>
        <h3 className={styles.title}>转换历史记录</h3>
        {history.length > 0 ? (
          <table className={styles.historyTable}>
            <thead>
              <tr>
                <th className={styles.tableHeader}>时间</th>
                <th className={styles.tableHeader}>类型</th>
                <th className={styles.tableHeader}>输入</th>
                <th className={styles.tableHeader}>结果</th>
              </tr>
            </thead>
            <tbody>
              {history.slice().reverse().map((item, index) => (
                <tr key={index}>
                  <td className={styles.tableCell}>{item.time}</td>
                  <td className={styles.tableCell}>
                    {item.type === 'timestamp-to-date' ? '时间戳转日期' : '日期转时间戳'}
                  </td>
                  <td className={styles.tableCell}>
                    {item.input} {item.inputUnit === 'seconds' ? '秒' : item.inputUnit === 'milliseconds' ? '毫秒' : item.outputUnit === 'seconds' ? '秒' : '毫秒'}
                  </td>
                  <td className={styles.tableCell}>{item.result}</td>
                </tr>
              ))}
            </tbody>
          </table>
        ) : (
          <div className={styles.historyEmpty}>暂无转换记录</div>
        )}
      </div>
    </div>
  );
};

// 样式定义
const containerStyle = {
  minHeight: '100vh',
  display: 'flex',
  flexDirection: 'row',
  justifyContent: 'space-between',
  alignItems: 'flex-start',
  backgroundColor: 'white',
  padding: '40px 20px',
  gap: '20px',
};

const panelsContainer = {
  display: 'flex',
  gap: '20px',
  width: '100%',
  maxWidth: '800px',
};

const panelStyle = {
  flex: 1,
  padding: '20px',
  border: '1px solid #e0e0e0',
  borderRadius: '8px',
};

const panelTitleStyle = {
  marginTop: 0,
  marginBottom: '20px',
  color: '#333',
  fontSize: '18px',
  borderBottom: '1px solid #eee',
  paddingBottom: '10px',
};

const inputWithUnit = {
  display: 'flex',
  gap: '10px',
  marginBottom: '15px',
};

const selectStyle = {
  width: '100%',
  padding: '12px',
  borderRadius: '4px',
  transition: 'backgroundColor 0.3s',
  border: '1px solid #1890ff',
  color: '#1890ff',
  backgroundColor: 'white',
  fontSize: '14px',
};

const convertButtonStyle = {
  width: '100%',
  padding: '12px',
  backgroundColor: '#1890ff',
  color: 'white',
  border: 'none',
  borderRadius: '4px',
  cursor: 'pointer',
  fontSize: '16px',
  marginBottom: '15px',
};

const resultContainer = {
  marginTop: '15px',
  padding: '10px',
  backgroundColor: '#f9f9f9',
  borderRadius: '4px',
};

const resultLabel = {
  fontSize: '14px',
  color: '#666',
  marginBottom: '5px',
};

const resultValue = {
  fontSize: '16px',
  fontWeight: 'bold',
  color: '#333',
};

const currentTimestampContainer = {
  marginTop: '15px',
  fontSize: '13px',
  color: '#666',
  textAlign: 'center',
};

const dateInputStyle = {
  width: '100%',
  padding: '10px',
  borderRadius: '4px',
  border: '1px solid #1890ff',
  fontSize: '14px',
  marginBottom: '15px',
  boxSizing: 'border-box',
};

const cardStyle = {
  backgroundColor: 'white',
  borderRadius: '12px',
  boxShadow: '0 4px 20px rgba(0, 0, 0, 0.1)',
  padding: '30px',
  width: '100%',
  flex: 1,
};

const titleStyle = {
  color: '#333',
  marginBottom: '25px',
  textAlign: 'center',
  fontSize: '24px',
};

const inputGroup = {
  marginBottom: '20px',
};

const labelStyle = {
  display: 'block',
  marginBottom: '8px',
  color: '#555',
  fontSize: '14px',
};

const inputStyle = {
  width: '100%',
  padding: '12px',
  borderRadius: '6px',
  border: '1px solid #1890ff',
  fontSize: '16px',
  boxSizing: 'border-box',
};

const errorStyle = {
  color: '#1890ff',
  padding: '10px',
  backgroundColor: '#e6f7ff',
  borderRadius: '6px',
  marginBottom: '15px',
  fontSize: '14px',
};

export default TimestampConverter;